import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:lovify/widgets/aq_input.dart';

class AQCake extends StatefulWidget {
  final String? label;
  final String? placeholder;
  final IconData? prefixIcon;
  final IconData? suffixIcon;
  final void Function(DateTime)? onChanged;
  final DateTime? initialDate;
  final DateTime? defaultValue; // New parameter for default value

  const AQCake({
    super.key,
    this.label,
    this.placeholder,
    this.onChanged,
    this.prefixIcon,
    this.suffixIcon,
    this.initialDate,
    this.defaultValue, // Add to constructor
  });

  @override
  AQCakeState createState() => AQCakeState();
}

class AQCakeState extends State<AQCake> {
  late TextEditingController _controller;
  DateTime? selectedDate;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(
      text: widget.initialDate != null
          ? DateFormat('yyyy-MM-dd').format(widget.initialDate!)
          : widget.defaultValue != null
              ? DateFormat('yyyy-MM-dd').format(widget.defaultValue!)
              : '',
    );
    selectedDate = widget.initialDate ?? widget.defaultValue;
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Future<void> _pickDate(BuildContext context) async {
    DateTime? newSelectedDate = await showDatePicker(
      context: context,
      initialDate: selectedDate ?? DateTime.now(),
      firstDate: DateTime(1900),
      lastDate: DateTime.now(),
      builder: (context, child) {
        return Theme(
          data: ThemeData.dark().copyWith(
            colorScheme: const ColorScheme.dark(
              primary: Color(0xFFFF5D5B),
              onPrimary: Colors.white,
              surface: Colors.white,
              onSurface: Colors.black,
            ),
            dialogBackgroundColor: Colors.white,
          ),
          child: child!,
        );
      },
    );

    if (newSelectedDate == null) return;

    String formattedDate = DateFormat('yyyy-MM-dd').format(newSelectedDate);

    setState(() {
      selectedDate = newSelectedDate;
      _controller.text = formattedDate;
    });

    widget.onChanged?.call(newSelectedDate);
  }

  @override
  Widget build(BuildContext context) {
    return AQInput(
      controller: _controller,
      readOnly: true,
      label: widget.label,
      placeholder: widget.placeholder ?? "",
      prefixIcon: widget.prefixIcon,
      suffixIcon: widget.suffixIcon,
      onTap: (_) => _pickDate(context),
    );
  }
}
